package com.qf.efserver.user.personaldata.service.impl;

import com.qf.common.core.entity.UsersWeight;
import com.qf.common.core.utils.DateUtils;
import com.qf.common.core.utils.TokenUtils;
import com.qf.common.core.utils.UserUtils;
import com.qf.common.redis.utils.RedisUtils;
import com.qf.efserver.user.personaldata.mapper.UsersWeightMapper;
import com.qf.efserver.user.personaldata.service.UsersService;
import com.qf.efserver.user.personaldata.service.UsersWeightService;
import com.qf.efserver.user.personaldata.vo.WeightVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * ---做一个内核强大的人---
 *
 * @author HuaZi
 * @date 2024/11/13
 * @desc 希望我们都能遇到真诚的人
 */
@Service
@Slf4j
public class UsersWeightServiceImpl implements UsersWeightService {
    @Resource
    private UsersWeightMapper usersWeightMapper;
    @Resource
    private UsersService usersService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public List<WeightVO> getWeights() {
        List<UsersWeight> usersWeights = usersWeightMapper.selectWeights(UserUtils.getUid());
        System.out.println(usersWeights);
        List<WeightVO> weightVOS = usersWeights.stream().map(item -> {
            Integer weekTime = item.getWeekTime();
            String time = null;
            switch (weekTime) {
                case 0:
                    time = "周一";
                    break;
                case 1:
                    time = "周二";
                    break;
                case 2:
                    time = "周三";
                    break;
                case 3:
                    time = "周四";
                    break;
                case 4:
                    time = "周五";
                    break;
                case 5:
                    time = "周六";
                    break;
                case 6:
                    time = "周日";
                    break;
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(item.getCreateTime());
            try {
                Date date = simpleDateFormat.parse(format);
                UsersWeight usersWeight = usersWeightMapper.selectByUidAndCreateTime(UserUtils.getUid(), date);
                if (usersWeight != null) {
                    if (usersWeight.getWeekTime() == null) {
                        usersWeightMapper.updateWeekTime(weekTime, UserUtils.getUid(), date);
                    }
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            WeightVO weightVO = new WeightVO();
            weightVO.setWeight(item.getWeight());
            weightVO.setTime(time);
            return weightVO;
        }).collect(Collectors.toList());
        return weightVOS;
    }

    /**
     * @param weight
     */
    @ApiOperation(value = "新增体重", notes = "通过id来修改体重")
    @Override
    public void insertWeight(Double weight) {
        Integer uid = TokenUtils.getUidFromToken();
        String today = DateUtils.today();
        //redis中存储当天所有用户的体重数据
        //key值为前缀+今日日期，存储的数据是hash表，filed值为uid，value为用户一天存储的体重的链表
        String key = String.format("weight:time:%s", today);
        String s = uid.toString();

        List<Double> weights = new ArrayList<>();
        //ret为true代表redis中有今天的数据
        boolean ret = RedisUtils.hasKey(key);
        //获取redis中的所有filed值即今天所有记录体重的用户id
        Map<Object, Object> map = RedisUtils.hashGetAll(key);
        //ret2为redis中今天数据的filed(用户id)值--为false表示redis中没有所登录用户的体重信息
        boolean ret2 = false;

        Set<Object> objects = map.keySet();
        for (Object o : objects) {
            String id = (String) o;
            if (s.equals(id)) {
                ret2 = true;
            }
        }
        if (!ret || !ret2) {
            weights.add(weight);
            RedisUtils.hashPut(key, s, weights);
            RedisUtils.expire(key, 60 * 60 * 24 * 7);
            UsersWeight usersWeight = new UsersWeight();
            usersWeight.setCreateTime(new Date());
            usersWeight.setUpdateTime(new Date());
            usersWeight.setWeight(weight);
            usersWeight.setUid(uid);
            usersWeightMapper.insert(usersWeight);
        } else {
            List<Double> list = (ArrayList) RedisUtils.hashGet(key, s);
            list.add(weight);
            RedisUtils.hashPut(key, s, list);
            usersService.updateWeight(weight);
        }
        updateWeight();
    }

    @Override
    public void updateWeight() {
        //从redis中获取今天的所有用户和用户的所有值
        String today = DateUtils.today();
        String key = String.format("weight:time:%s", today);
        Map<Object, Object> map = RedisUtils.hashGetAll(key);
        //第一个值为uid
        //第二个值为体重list
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Integer uid = Integer.parseInt((String) entry.getKey());
            List<Double> values = (List) entry.getValue();
            Double weight = values.get(values.size() - 1);
//                usersWeightMapper.update(null,
//                        new LambdaUpdateWrapper<UsersWeight>()
//                                .set(UsersWeight::getWeight,weight)
//                                .eq(UsersWeight::getUid,uid)
//                                .eq(UsersWeight::getCreateTime,today));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date createTime = null;
            try {
                createTime = simpleDateFormat.parse(today);
                usersWeightMapper.update(uid, weight, createTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }
    }
}
